<?php	
	require "journalUtils.php";
	require "../application/dataAccess.php";
	
	$daAccess = new dataAccess();
	
	session_start();
	$title = $_GET['text'];
	if ($_GET['text'])
	{
		$result = "";
		$da = new RetriveData();						
		if ($_GET['type'] == 'journal')
		{
			header('Content-type: application/json');
			$result = $da->requestJournal($title);
			echo json_encode($result);
		}
		else if ($_GET['type'] =='compose_assigment')
		{			
			header('Content-Type: text/html; charset=utf-8');
			$result = $da->getSuggestionByComposeAssigmentTitle($title);			
			echo "<div class='header-relevant'>";
			echo "<div class='header-relevant-title'>";
			echo "<span>Results:<span class='relevant-keyword'>" . $title . "</span></span>";
			echo"</div>";
			echo "<div class='header-relevant-button'>";
			echo "<input type='button' value='Close' onclick='$(this.parentNode.parentNode.parentNode).fadeOut()'/>";
			echo"</div>";
			echo"<div style='clear:both'></div>";
			echo"</div>";			
			echo "<div class='content-relevant'>";
			if (count($result) > 0)
			{
				foreach($result as $item)
				{
					if ($item[0] != "")
						echo "<p class='item'><a href='" . $item[1] . "' target='_blank'>" . $item[0] . "</a><br/><span>" . substr($item[1], 0, 35) . "...</span></p>";
					else
						echo "<hr/>";
				}
			}
			else
			{
				echo "<p class='item'>Data was not found</p>";
			}
			echo "</div>";
			
			//send email after search			
			$sql = "SELECT Email, FirstName FROM users u WHERE u.id = '" . $_SESSION['user_id'] . "'";
			
			$query = mysql_query($sql);
			if ($query)
			{
				$row = mysql_fetch_row($query);				
				$email = $row[0];
				
				$header  = 'MIME-Version: 1.0' . "\r\n";
				$header .= 'Content-type: text/html; charset=utf-8' . "\r\n";			
				$header .= 'From: support@studysage.com.au' . "\r\n";				
				$subject = "Suggested book titles";
				$content = '<p style="color:#7030A0"><b>Dear ' . $row[1] . ',</b></p>';
				$content .= '<p>Here below is a list of suggested book titles that may have practical relevance to your inquiry/essay. Click the links given to purchase them if need be.</p>';
				
				$data = $da->getBooksFromAmazon($title);
				$index = 0;
				foreach($data as $item)
				{	
					$content .= "<p class='item'><a href='" . $item->url . "' target='_blank'>" . $item->title . "</a></p>";					
					if ($index++ == 2)
					{
						break;
					}
				}
				
				$index = 0;
				$data = $da->getGoogleBook($title);				
				foreach($data as $item)
				{
					$content .= "<p class='item'><a href='" . $item[1] . "' target='_blank'>" . $item[0] . "</a></p>";
					if ($index++ == 5)
					{
						break;
					}
				}
				
				$content .= '
				<br/>
				Kind Regards,
				<br/>
				Support Team
				<br/><br/>
				http://www.studysage.com.au
				';					
				
				mail($email, $subject, $content, $header);
			}
		}				
	}
?>